import RootStore, { type IMMessage } from "@xkit-yx/im-store";
// @ts-ignore
import { NimKitCore } from "@xkit-yx/core-kit/dist/uniapp-nim-core";
import { getMsgContentTipByType } from "./msg";
import { STORAGE_KEY } from "./constants";
import { useImStore } from "@/stores";
import { customNavigateTo } from "./customNavigate";
const IM_APPKEY = import.meta.env.VITE_IM_APPKEY;

const isWxApp = true;
export function initNim(opts : { account : string; token : string }) {
	const imStore = useImStore();
	console.log('==== init nim ====');

	// 保存登录信息
	// @ts-ignore
	uni.setStorage({
		key: STORAGE_KEY,
		data: opts,
		success: function () {
			console.log("保存登录信息success");
		},
	});
	// @ts-ignore
	uni.$$nimAuth = {
		appkey: IM_APPKEY, // 请填写你的appkey
		account: opts.account, //  "hevmvzkdlkl8", // 请填写你的account
		token: opts.token, // "1a7b75462032300273f706f9f2b5524f", // 请填写你的token
		// account: 'test1001',
		// token: '83776386bc383b883e810e8ef031d45f',
	};
	console.log('==== uni.$$nimAuth ====', uni.$$nimAuth);
	// @ts-ignore
	const nim = (uni.$UIKitNIM = new NimKitCore({
		initOptions: {
			// @ts-ignore
			...(uni.$$nimAuth),
			lbsUrls: isWxApp
				? ["https://lbs.netease.im/lbs/wxwebconf.jsp"]
				: ["https://lbs.netease.im/lbs/webconf.jsp"],
			linkUrl: isWxApp ? "wlnimsc0.netease.im" : "weblink.netease.im",
			needReconnect: true,
			/**
			 * 使用固定设备ID，
			 */
			isFixedDeviceId: true,
			// "reconnectionAttempts": 5,
			debugLevel: "debug",
			// ...opts,
		},
		platform: "UniApp",
	}));

	// nim.on('sessions', (sessions) => {
	// 	console.log('sessionsABC111', sessions);
	// })

	// nim.on('updateSession', (sessions) => {
	// 	console.log('sessionsABC222', sessions);
	// })

	// @ts-ignore
	uni.$$nim = nim;


	// @ts-ignore
	const store = (uni.$UIKitStore = new RootStore(nim, {
		addFriendNeedVerify: false,
		teamBeInviteMode: "noVerify",
		teamJoinMode: "noVerify",
		teamUpdateExtMode: "manager",
		teamUpdateTeamMode: "manager",
		teamInviteMode: "manager",
		sendMsgBefore: async (options : any, type : IMMessage["type"]) => {
			const pushContent = getMsgContentTipByType({
				body: options.body,
				type,
			});
			const yxAitMsg = options.ext
				? options.ext.yxAitMsg
				: { forcePushIDsList: "[]", needForcePush: false };

			// 如果是 at 消息，需要走离线强推
			// @ts-ignore
			const { forcePushIDsList, needForcePush } = yxAitMsg
				? // @ts-ignore
				store.msgStore._formatExtAitToPushInfo(yxAitMsg, options.body)
				: { forcePushIDsList: "[]", needForcePush: false };

			console.log("forcePushIDsList: ", forcePushIDsList);

			// 不同产商的推送消息体
			const { scene, to } = options;
			const pushPayload = JSON.stringify({
				// oppo
				oppoField: {
					click_action_type: 4, // 参考 oppo 官网
					click_action_activity: "", // 各端不一样 TODO
					action_parameters: { sessionId: scene, sessionType: to }, // 自定义
				},

				// vivo
				vivoField: {
					pushMode: 0, //推送模式 0：正式推送；1：测试推送，不填默认为0
				},

				// huawei
				hwField: {
					click_action: {
						type: 1,
						action: "", // 各端不一样 TODO
					},
					androidConfig: {
						category: "IM",
						data: JSON.stringify({ sessionId: to, sessionType: scene }),
					},
				},

				// 通用
				sessionId: to,
				sessionType: scene,
			});

			const pushInfo : any = {
				needPush: true,
				needPushBadge: true,
				pushPayload: "{}",
				pushContent,
				needForcePush,
				forcePushIDsList,
				forcePushContent: pushContent,
			};
			return { ...options, pushInfo };
		},
	}));
	nim.connect();
	setTimeout(() => {
		imStore.setInit(true);
	}, 1000);
}


export function sendTextMsg(data : {
	to ?: string; // 发送给谁
	body : string; // 发送内容
	ext ?: string | number; // 扩展字段
}, toChatPage : boolean, callback ?: Function) {
	const imStore = useImStore();
	const [first] = imStore.chatUserList;
	if (!first) {
		uni.showToast({
			icon: 'none',
			title: '未配置IM客服'
		})
		return;
	}
	if (!data.to) {
		data.to = first.accId;
	}
	// @ts-ignore
	uni.$UIKitStore.msgStore
		.sendTextMsgActive({
			scene: 'p2p',
			...data
		})
		.finally((res : any) => {
			console.log('==== im.sendTextMsg ====', res);
			if (toChatPage) {
				toChat(data.to);
			}
			callback?.();
		})
}

/**
 * 
 * @param {string} id 账号
 * @return 
 */
export async function toChat(id : string) {
	// @ts-ignore
	await uni.$UIKitStore.uiStore.selectSession(`p2p-${id}`);
	customNavigateTo({
		url: '/pages/message/chat/index',
	})
}